'''
游戏需要窗口化（1600x900），最前面窗口

'''

import pyautogui
import pydirectinput
import time
import keyboard
import pygetwindow #兼容旧代码
import pygetwindow as gw
import ctypes
import win32gui
import win32con
import random
import sys
import io
import ctypes
import os
import fileinput
import subprocess
import progressbar
import threading
import datetime
from PIL import ImageGrab,Image
import utils


#游戏基本信息
game_title = '原神'
file_path = r'D:\miHoYo Launcher\games\Genshin Impact Game\YuanShen.exe'

# 窗口位置，游戏启动后获取
x1 = 0
y1 = 0
zzz = 0
#每一轮战斗分配的时间 s （根据自己账号练度调整）
fight_time_max = 300
fighting = False
award1ing = False


def getXY():
    # 获取指定标题的程序窗口对象
    program_window = pygetwindow.getWindowsWithTitle('原神')[0]
    # 获取窗口左上角的位置
    top_left_position = program_window.topleft
    print(top_left_position)
    global x1,y1;
    x1 = top_left_position.x
    y1 = top_left_position.y



def drag(point):
    if point=="up":
        pyautogui.moveTo(1267, 255)
        pyautogui.dragTo(1267, 646, 2, button='left')  # 按住鼠标左键，用0.5s将鼠标拖拽至1230，458
    elif point=="down":
        pyautogui.moveTo(1267, 646)
        pyautogui.dragTo(1267, 255, 2, button='left')  
    elif point=="left":
        pyautogui.moveTo(614, 62)
        pyautogui.dragTo(1014, 62, 2, button='left')  
    elif point=="right":
        pyautogui.moveTo(1014, 62)
        pyautogui.dragTo(614, 62, 2, button='left')      
    time.sleep(1)
def turn(o,h=0):
    pydirectinput.moveRel(xOffset=o,yOffset=h,duration=0.4,relative=True)
    r()
def walk(t):
    pydirectinput.keyDown("w")#按键
    time.sleep(t)
    pydirectinput.keyUp("w")
    rr()
def r():
    random_number = random.uniform(0.7, 0.9)
    time.sleep(random_number)
def rr():
    random_number = random.uniform(1.5, 2.0)
    time.sleep(random_number)
def rrr():
    time.sleep(15)
def sleep(t):
    time.sleep(t)#单位=秒
def click(x,y):
    pydirectinput.click(x+x1, y+y1)#点击
    rr()
def press(m):
    pydirectinput.press(m)#按键
    rr()
def long_press(m,t=1):
    # pydirectinput.press(m)#按键
    pydirectinput.keyDown(m)
    sleep(t)
    pydirectinput.keyUp(m)
    rr()
def getpngfromShot2(png,_threshold=0.8,_show_print=True):
    small = Image.open(f"yuan/{png}.png")
    big = pyautogui.screenshot(region=[x1,y1,xing.width,xing.height])
    point = utils.getpngfromShot(small,big,_threshold=_threshold)
    if _show_print:
        print(png,point)
    return point
def make_window_active(window_title):
    try:
        # 获取当前活动窗口的句柄
        foreground_window = win32gui.GetForegroundWindow()

        # 获取目标窗口
        windows = gw.getWindowsWithTitle(window_title)
        if not windows:
            print(f"No windows found with title '{window_title}'.")
            return False
        
        target_window = windows[0]._hWnd  # 获取第一个匹配窗口的句柄
        
        # 判断目标窗口是否为当前活动窗口
        if foreground_window == target_window:
            print(f"Window '{window_title}' is already the active window.")
            return True
        
        # 将窗口设置为活动窗口
        win32gui.ShowWindow(target_window, win32con.SW_RESTORE)  # 恢复窗口（如果它被最小化）
        win32gui.SetForegroundWindow(target_window)  # 设置为前景窗口
        
        print(f"Window '{window_title}' has been set as the active window.")
        return True
    except Exception as e:
        print(f"Error: {e}")
        return False
def is_window_active(window_title):
    try:
        # 获取当前活动窗口的句柄
        foreground_window = ctypes.windll.user32.GetForegroundWindow()

        # 获取所有窗口
        windows = pygetwindow.getWindowsWithTitle(window_title)
        if not windows:
            print(f"No windows found with title '{window_title}'.")
            return False

        # 获取目标窗口的句柄
        target_window = windows[0]._hWnd  # 获取第一个匹配窗口的句柄
        
        # 判断目标窗口是否为当前活动窗口
        if foreground_window == target_window:
            print(f"Window '{window_title}' is the active window.")
            return True
        else:
            print(f"Window '{window_title}' is not the active window.")
            return False
    except Exception as e:
        print(f"Error: {e}")
        return False
def move_XY(window_title,new_x,new_y):
    try:
        # 获取窗口对象
        windows = pygetwindow.getWindowsWithTitle(window_title)
        if not windows:
            print(f"No windows found with title '{window_title}'.")
            return
        
        # 选择第一个匹配的窗口
        window = windows[0]
        hwnd = window._hWnd

        # 获取当前窗口的位置信息
        rect = window._rect
        current_width = rect.width
        current_height = rect.height

        # 使用 ctypes 调用 MoveWindow API 移动窗口
        ctypes.windll.user32.MoveWindow(hwnd, new_x, new_y, current_width, current_height, True)
        print(f"Window '{window_title}' moved to ({new_x}, {new_y}) while keeping its size.")
    except Exception as e:
        print(f"Error: {e}")
def getXY():
    #init
    global game_title
    
    while(True):
        make_window_active(game_title)
        sleep(0.5)
        if is_window_active(game_title):
            sleep(0.5)
            move_XY(game_title,0,0)
            break

    # 获取指定标题的程序窗口对象
    program_window = pygetwindow.getWindowsWithTitle(game_title)[0]
    # 获取窗口左上角的位置
    top_left_position = program_window.topleft
    print(top_left_position)
    global x1,y1,xing;
    x1 = top_left_position.x
    y1 = top_left_position.y
    xing = program_window
# 进度条
def getBar(_maxval):
    bar = progressbar.ProgressBar(maxval=_maxval, widgets=[
        progressbar.Bar('=', '[', ']'), ' ', progressbar.Percentage()
    ])
    bar.start()
    return bar
def waitpng(png,time):
    bar = getBar(time)
    for i in range(time):
        loc = getpngfromShot2(png,_show_print=False)
        if loc!=0:break;
        bar.update(i)
        sleep(1)
    bar.finish()
    return loc


# 打开地图并复位
def open_rst_map(place):
    press('m')# 打开地图
    click(1531, 884)# 打开右下角地区列表
    click(1220,610)# 选择尘歌壶地区
    click(1531, 884)# 打开右下角地区列表
    if place=="mengde":
        click(1232,160)# 选择蒙德地区
    elif place=="liyue":
        click(1486,156)# 选择璃月地区
    elif place=="daoqi":
        click(1197,236)# 选择稻妻
    elif place=="xuni":
        click(1465,238)# 须弥
    elif place=="fengdan":#TODO 加强功能
        click(1207,322)# 枫丹
        click(805,487) #核心锚点
        loc = getpngfromShot2("传送锚点")
        if loc!=0:
            click(loc[0],loc[1]) #传送锚点
            click(1407,881) #传送
            waitpng("Enter",20)
            print("传送完毕。。")
        else:
            print("没找到 传送锚点")
            click(1552,66)#右上角关闭按钮
            click(1552,66)#右上角关闭按钮
    elif place=="nata":
        click(1448,329)# 纳塔
    else:
        #尘歌壶
        click(1562, 62)# 右上角关闭按钮
        pass
        
    
    # for i in range(5):
    #     click(41,581)# 地图缩小按钮
    # for i in range(2):
    #     click(41,394)# 地图放大按钮

#自动打怪连招
# 钟离-去角落-水神-雷神-  （钟离-水龙王）x2
def auto_fighting():
    #钟离上场
    press("1") #钟离上场
    pydirectinput.keyDown("e") #长按 e
    time.sleep(0.7)
    pydirectinput.keyUp("e")
    sleep(0.7)
    
    #去角落
    turn(1200)
    walk(5)
    
    #水神上场
    press("2") #水神上场
    press("e") # e
    sleep(0.7)

    #雷神上场
    press("3") #雷神上场
    press("e") # e
    sleep(0.7)

    #钟离上场
    press("1") #钟离上场
    pydirectinput.keyDown("e") #长按 e
    time.sleep(0.7)
    pydirectinput.keyUp("e")
    sleep(0.7)
    
    #水龙王上场
    press("4") #水龙王上场
    press("e") # e
    sleep(0.7)
    pydirectinput.mouseDown()
    for k in range(300): # 转3秒
        ctypes.windll.user32.mouse_event(0x01, 100, 0, 0, 0)
        time.sleep(0.01)
    pydirectinput.mouseUp()
    sleep(0.7)

    #雷神上场
    press("3") #雷神上场
    press("e") # e
    sleep(0.7)
    press("q")
    sleep(1.5)

    #钟离上场
    press("1") #钟离上场
    pydirectinput.keyDown("e") #长按 e
    time.sleep(0.7)
    pydirectinput.keyUp("e")
    sleep(0.7)

    #水神上场
    press("2") #水神上场
    press("e") # e
    sleep(0.7)

    #水龙王上场
    press("4") #水龙王上场
    press("e") # e
    sleep(0.7)
    pydirectinput.mouseDown()
    for k in range(300): # 转3秒
        ctypes.windll.user32.mouse_event(0x01, 100, 0, 0, 0)
        time.sleep(0.01)
    pydirectinput.mouseUp()
    sleep(0.7)

    #水龙王上场
    pydirectinput.mouseDown()
    sleep(4)
    for k in range(300): # 转3秒
        ctypes.windll.user32.mouse_event(0x01, 100, 0, 0, 0)
        time.sleep(0.01)
    pydirectinput.mouseUp()
    sleep(0.7)

    #水龙王上场
    press("e") # e
    sleep(0.7)
    pydirectinput.mouseDown()
    for k in range(300): # 转3秒
        ctypes.windll.user32.mouse_event(0x01, 100, 0, 0, 0)
        time.sleep(0.01)
    pydirectinput.mouseUp()
    sleep(0.7)

# todo
def gotoBen():
    # open_rst_map("daoqi")
    # drag("left") 
    # click(146,835) # 绝缘本位置
    # click(1400,870) # 传送按钮
    # sleep(15) # 等待传送完毕，需要点时间

    # walk(2) # 向前走
    # press("f") # 按 f键 开启秘境
    # sleep(5) # 等待动画
    # click(1413,874) #单人挑战按钮
    # sleep(2)
    # click(59,880) #选择 自动打怪队伍
    # pyautogui.moveTo(200, 200)
    # pyautogui.dragTo(200, 750, 2, button='left')   #划到第一个队伍
    # sleep(2)
    # click(200,200) #选择第一个队伍
    # sleep(2)
    # click(200,880) #确认队伍按钮
    # sleep(2)
    # click(1413,874) #开始挑战按钮
    # sleep(15)

    click(200,200) #点击任意位置关闭 提示
    walk(3.5) #向前走，开启挑战

    press("f")
    auto_fighting() #战斗
     
    #战斗结束后走到领奖台
    # ctypes.windll.user32.mouse_event(0x01, -4000, 0, 0, 0)
    # walk(2.5)
    # ctypes.windll.user32.mouse_event(0x01, 2600, 0, 0, 0)
    # walk(6)

    #领取奖励
    # press("f")
    # sleep(0.7)
    # click(960,655)#选择用普通的树脂
    # sleep(10)

    #退出秘境
    # click(624,855)
    # sleep(15)

def clickOptions(n):
    if n==1:
        click(1382,700) #第一个选项
    elif n==2:
        click(1382,640) #第二个选项
    elif n==3:
        click(1382,579) #第三个选项
    elif n==4:
        click(1382,516) #第四个选项
    elif n==5:
        click(1382,457) #第五个选项
    elif n==6:
        click(1382,388) #第六个选项

#邮箱
def email():
    press("esc")
    click(40,537) #邮件
    click(188,880) #全部领取
    click(188,880) #全部领取
    rr()
    press("esc")
    press("esc")

    pass

#探索派遣 old
def dispatch():
    open_rst_map("fengdan")
    for i in range(5):
        click(41,394)# 地图放大按钮
    click(800,481) #枫丹
    click(1408,641) # 选择锚点
    click(1400,875) # 传送
    sleep(20) #等待传送

    turn(-1000)
    walk(3)

    press("f") #凯瑟琳
    press("f") #对话：向着星辰与深渊
    click(1200,510) #探索派遣
    click(188,880) #全部领取
    click(937,886) #再次派遣
    press("esc")



    pass

#尘歌壶金币
def chengehu():
    open_rst_map("chen")
    click(800,482) #宅邸
    click(1386,640) #
    click(1400,875) # 传送
    waitpng("Enter",20)

    turn(-1000)
    walk(1)

    press("f") #阿圆
    rr()
    press("f") #对话：这片洞天啊
    r()
    clickOptions(6) #信任等阶
    r()
    click(890,786) #金币
    click(1510,627) #好感度
    press("esc")
    rr()
    clickOptions(1) #再见
    rr()
    press("f")

    pass

# 纪行
def jixing():
    ''' old
    pydirectinput.keyDown("alt")
    r()
    click(1234,70) #纪行
    r()
    pydirectinput.keyUp("alt")
    click(800,70) #任务
    click(1444,845) #一键领取
    rr()
    click(720,70) #珍珠纪行
    click(1444,845) #一键领取
    press("esc")
    press("esc")
    '''
    sleep(2)
    press("esc")
    loc = getpngfromShot2("珍珠纪行")
    if loc!=0:
        click(loc[0],loc[1])
        sleep(1)
        click(808,77)#任务
        click(1461,848)#一键领取
        sleep(1)
        press("esc")
        press("esc")
    else:
        print("没有找到 珍珠纪行 ")
        press("esc")

#月卡
def month_card():
    sleep(2)
    loc = getpngfromShot2("点击领取今日空月祝福奖励")
    if loc!=0:
        print("有月卡领取")
        click(loc[0],loc[1])
        sleep(3)
        click(loc[0],loc[1])
        sleep(1)
    else:
        print("没有月卡领取")
# 每日委托
def daily():
    sleep(2)
    press("f1")
    click(246,316) #委托标签
    click(1296,664) #领取
    sleep(1)
    press("esc")
    press("esc")

    sleep(1)
    open_rst_map("fengdan")
    turn(-500)#左转看向凯瑟琳
    walk(3)

    press("f") #凯瑟琳
    sleep(1)
    press("f") #对话：向着星辰与深渊
    sleep(1)
    click(1184,392) #领取 每日委托 奖励
    sleep(1)
    click(1184,392) 
    sleep(1)
    click(1184,392)
    sleep(1)

    press("f") #凯瑟琳
    sleep(1)
    press("f") #对话：向着星辰与深渊
    sleep(1)
    click(1176,519) #探索派遣
    sleep(1)
    click(144,884) #全部领取
    sleep(1)
    click(968,883) #探索派遣
    sleep(1)
    press("esc")




# play game
def play_old():
    

    #邮箱
    sleep(2)
    email()

    #探索派遣
    sleep(2)
    dispatch()

    #纪行
    sleep(2)
    jixing()

    #尘歌壶
    sleep(2)
    chengehu()

    


    print("end...")

########################################################
def testtttttttttt():
    '''
    print("=======check_png=========")

    
    #1600x900 yuan/地脉花宝箱.png 0.75
    # x1,y1 = point[0],point[1]
    pydirectinput.moveRel(xOffset=0,yOffset=10000,duration=0.4,relative=True)
    sleep(1)
    pydirectinput.moveRel(xOffset=0,yOffset=-5000,duration=0.4,relative=True)
    sleep(1)
    

    # small = Image.open("zzz/领取.png")
    # small = Image.open("xing/霜晶之形.png")
    small = Image.open("yuan/地脉花宝箱.png")
    # small.show()
    big = pyautogui.screenshot(region=[x,y,xing.width,xing.height])
    # big.show()
    point = getpngfromShot(small,big,0.75,False)
    print("png point = ",point)

    
    x1,y1 = point[0],point[1]
    while True:
        sleep(1)
        small = Image.open("yuan/地脉花宝箱.png")
        big = pyautogui.screenshot(region=[x,y,xing.width,xing.height]) 
        point = getpngfromShot(small,big,0.75,False)
        print("png point = ",point)
        x1,y1 = point[0],point[1]
        if x1<600:
            # deep = (700-x1)*3
            # print(f"deep={deep}")
            print("left1")
            pydirectinput.moveRel(xOffset=-300,yOffset=0,duration=0.4,relative=True)
        elif x1<730:
            print("left2")
            pydirectinput.moveRel(xOffset=-100,yOffset=0,duration=0.4,relative=True)
        elif x1>1000:
            # deep = (900-x1)*3
            # print(f"deep={deep}")
            print("right2")
            pydirectinput.moveRel(xOffset=300,yOffset=0,duration=0.4,relative=True)
        elif x1>880:
            # deep = (900-x1)*3
            # print(f"deep={deep}")
            print("right1")
            pydirectinput.moveRel(xOffset=100,yOffset=0,duration=0.4,relative=True)
        else:
            while True:
                pydirectinput.keyDown("w")#按键
                time.sleep(1)
                pydirectinput.keyUp("w")
                sleep(1)
                small = Image.open("yuan/接触征讨之花.png")
                big = pyautogui.screenshot(region=[x,y,xing.width,xing.height]) 
                point = getpngfromShot(small,big,0.75,False)
                if point!=0:
                    print("接触征讨之花")
                    break
                else:
                    print("nonono")
            break
    # else:
    #     if y1<190:
    #         pydirectinput.moveRel(xOffset=2000,yOffset=0,duration=0.4,relative=True)
    
    return point
    '''

def action_fight():
    while fighting:
        # 钟离上盾
        pydirectinput.press("4")
        sleep(0.5)
        pydirectinput.keyDown("e")
        sleep(1)
        pydirectinput.keyUp("e")
        sleep(0.5)

        #水神召唤 宠物 两轮召唤一次
        pydirectinput.press("2")
        pydirectinput.press("e")
        sleep(0.5)

        #草神挂草
        pydirectinput.press("1")
        pydirectinput.press("e")
        sleep(0.5)

        #97忍
        pydirectinput.press("3")
        pydirectinput.press("e")
        sleep(0.5)
def fight(finish_png,t=fight_time_max):
    global fighting
    print("进入战斗。。。")
    bar = getBar(t)
    fighting = True
    fight_thread = threading.Thread(target=action_fight)
    fight_thread.start()
    for i in range(t):
        sleep(1)
        bar.update(i)
        small1 = Image.open(f"yuan/{finish_png}.png")
        small2 = Image.open(f"yuan/击败怪物.png")
        small3 = Image.open(f"yuan/剩余时间图标.png")
        big = pyautogui.screenshot(region=[x1,y1,xing.width,xing.height])
        point1 = utils.getpngfromShot(small1,big,_threshold=0.8)
        point2 = utils.getpngfromShot(small2,big,_threshold=0.8)
        point3 = utils.getpngfromShot(small3,big,_threshold=0.8)
        if point1!=0:break;
        if point2==0 and point3==0:break;
    fighting = False
    fight_thread.join()
    # click(1422,886) # 完成按钮
    bar.finish()
def action_get_award1():
    while award1ing:
        long_press("s",1)
        long_press("d",1)
        long_press("w",10)
def get_award1():#延迟太高，方法不行
    global award1ing
    sleep(2)
    print("拿奖励。。。")
    bar = getBar(60)
    award1ing = True
    award1_thread = threading.Thread(target=action_get_award1)
    award1_thread.start()
    for i in range(60):
        bar.update(i)
        big = pyautogui.screenshot(region=[x1,y1,xing.width,xing.height])
        small1 = Image.open(f"yuan/加载门_白底.png")
        small2 = Image.open(f"yuan/加载门_黑底.png")
        small3 = Image.open(f"yuan/元素图标_白底.png")
        small4 = Image.open(f"yuan/元素图标_黑底.png")
        point1 = utils.getpngfromShot(small1,big,_threshold=0.8)
        point2 = utils.getpngfromShot(small2,big,_threshold=0.8)
        point3 = utils.getpngfromShot(small3,big,_threshold=0.8)
        point4 = utils.getpngfromShot(small4,big,_threshold=0.8)
        print(point1,point2,point3,point4)
        if point1!=0 or point2!=0 or point3!=0 or point4!=0:break;
    award1ing = False
    award1_thread.join()
    # click(1422,886) # 完成按钮
    bar.finish()
def get_award2():
    sleep(2)
    turn(-1000)
    flag = 0
    for i in range(20):
        long_press("w",3)
        loc = getpngfromShot2("领取奖励")
        if loc!=0:
            press("f")
            sleep(0.5)
            loc = getpngfromShot2("使用浓缩树脂")
            if loc!=0:
                click(loc[0],loc[1])
            sleep(10)
            click(627,863)#退出秘境
            waitpng("Enter",10)
            flag = 1
            break;
    if flag==0:
        print("领取 失败 。。。")
        print("退出秘境 。，，")
        press("esc")
        click(979,670)#确认
        sleep(5)
        click(805,867)#退出秘境
        waitpng("Enter",10)

        
    

def cao_ben_type(ben="puRen"):
    sleep(2)
    click(1439,880) #单人挑战
    #判断 没体力时
    loc = getpngfromShot2("是否仍要挑战该秘境")
    if loc!=0:
        print("体力已用完。。。")
        press("esc")
        press("esc")
        return -1
    sleep(2)
    click(1439,880) #开始挑战
    waitpng("点击任意位置关闭",15)
    press("esc")
    press("4") #切出 钟离 来走路
    if(ben=="cao"):long_press("w",3.8)
    elif(ben=="puRen"):long_press("w",4.5)
    sleep(0.5)
    press("f") #启动挑战

    fight("挑战达成");

    press("4") #切出 钟离 来走路
    get_award2()

def team():
    sleep(2)
    press("l")
    waitpng("快速编队",10)
    click(76,889)#左下角打开队伍列表
    pyautogui.moveTo(x1+147,y1+338)
    for i in range(30):
        pyautogui.scroll(100)
    sleep(0.5)
    click(291,189)#第一个队伍
    click(279,880)#确认
    click(1422,880)#出战
    sleep(1)
    press("esc")

def blood():
    sleep(2)
    #芙芙 回血
    pydirectinput.press("2")
    pydirectinput.press("e")
    sleep(0.5)
    pydirectinput.mouseDown(button='left')
    sleep(1)
    pydirectinput.mouseUp(button='left')
    sleep(1)

    #97忍 回血
    pydirectinput.press("3")
    pydirectinput.press("e")
    sleep(5)

    #轮流切人 回血
    pydirectinput.press("1")
    sleep(5)
    pydirectinput.press("2")
    sleep(5)
    pydirectinput.press("4")
    sleep(10)

    #芙芙 恢复小宠物
    pydirectinput.press("2")
    pydirectinput.press("e")
    sleep(0.5)
    pydirectinput.mouseDown(button='left')
    sleep(1)
    pydirectinput.mouseUp(button='left')
    sleep(1)
def drive():
    sleep(2)
    press("f1")
    click(255,407)#秘境
    flag = 0
    for i in range(7):
        sleep(0.5)
        # loc = getpngfromShot2("缘觉塔")#TODO 现在是刷草本，其他以后再安排
        loc = getpngfromShot2("褪色的剧场")#TODO 仆人圣遗物
        if loc!=0:
            click(loc[0]+650,loc[1])
            sleep(3)
            click(1398,869)#传送
            waitpng("Enter",20)
            flag =1
            break;
        else:
            pyautogui.moveTo(x1+849,y1+351)#849,351
            for i in range(32):
                pyautogui.scroll(-100)
    if flag==0:
        print("没找到 材料。。。")
        press("esc")
    else:
        long_press("w")
        press("f")
        waitpng("单人挑战",10)
        return cao_ben_type()

def launch_game():
    sleep(2)
    global file_path
    #C:\Program Files\Star Rail\Game\StarRail.exe
    game_name = os.path.basename(file_path)
    call = 'TASKLIST','/FI',f'imagename eq {game_name}'
    output = subprocess.check_output(call).decode('cp1252')
    if game_name in output:
        isLaunchGame = True
    else:
        isLaunchGame = False
    
    #isLaunchGame = True
    if not isLaunchGame:
        print("not running")
        try:
            # 调用subprocess模块来启动.exe文件
            # subprocess.Popen(file_path,creationflags=subprocess.CREATE_NEW_CONSOLE)
            game_process = subprocess.Popen(['start', '', file_path], shell=True)
            result = 1
        except FileNotFoundError as e:
            print("未能找到指定的.exe文件")
            result = 0
        except Exception as e:
            print("发生错误：", str(e))
            result = 0
            
        if(result == 0):
            print("脚本结束...")
            exit()
        else:
            print("等待游戏启动...")
            bar=getBar(60)
            #启动程序到加载窗口出来
            for i in range(60):
                #print(str(i)+"-",end="")
                sleep(1) #等待游戏启动
                bar.update(i)
                if any(game_title in win.title for win in pygetwindow.getWindowsWithTitle(game_title)):
                    break
            bar.finish()

            #初始化位置，将程序放到左上角
            getXY()

            print("窗口加载开机动画，等待 点击进入 按钮")
            bar=getBar(30)
            for i in range(30):
                sleep(1) #等待 点击进入
                bar.update(i)
                loc = getpngfromShot2("点击进入",_show_print=False)
                if loc!=0:
                    break
                # click(500,500)
            # sleep(20)
            bar.finish()
            click(500,500) # 点击进入游戏

            #点击进入游戏 到 游戏画面
            print("点击进入 到 游戏画面")
            bar=getBar(30)
            for i in range(30):
                sleep(1) #等待 游戏画面
                bar.update(i)
                loc = getpngfromShot2("Enter",_show_print=False)
                if loc!=0:
                    print("没有月卡")
                    break
                loc = getpngfromShot2("点击领取今日空月祝福奖励",_show_print=False)
                if loc!=0:
                    print("有月卡")
                    click(loc[0],loc[1])
                    sleep(3)
                    click(loc[0],loc[1])
                    sleep(1)
                    break
            # sleep(20)
            bar.finish()



    else:
        print("running")
        getXY()


def play():
    print("启动游戏。。。")
    launch_game()

    # print("月卡。。。")
    # month_card()

    print("打材料....")
    open_rst_map("fengdan")
    team()
    while True:
        blood()
        if -1==drive():break;

    print("尘歌壶。。。") #这个地图 很多操作实现不了
    chengehu()

    open_rst_map("fengdan")
    print("每日委托。。。")
    daily()

    print("珍珠纪行。。。")
    jixing()

    

# main
if __name__ == "__main__":

    admin = ctypes.windll.shell32.IsUserAnAdmin()
    print("admin=="+str(admin))

    if admin:
        print("have admin")
        # 主程序写在这里
        try:
            play()
        except Exception as e:
            print(e)

        # input() # 防止退出
    else:
        print("not admin")
        # 以管理员权限重新运行程序
        if len(sys.argv) > 1:
            ctypes.windll.shell32.ShellExecuteW(None,"runas", sys.executable, __file__+" "+sys.argv[1], None, 3)
        else:
            ctypes.windll.shell32.ShellExecuteW(None,"runas", sys.executable, __file__, None, 3)
   

